package com.cloud.goal.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.goal.model.Goal;
import com.cloud.platform.IDao;
import com.cloud.platform.util.Constants;
import com.cloud.platform.util.StringUtil;

@Component
public class GoalService {

	@Autowired
	private IDao dao;
	
	/**
	 * remove goal
	 * 
	 * @param goalId
	 */
	public void removeGoal(String goalId) {
		if(StringUtil.isNullOrEmpty(goalId)) {
			return;
		}
		
		dao.removeById(Goal.class, goalId);
	}
	
	/**
	 * search user goals
	 * 
	 * @param userId
	 * @return
	 */
	public List<Goal> searchGoals(String userId) {
		String hql = "from Goal where uid = ? order by createTime";
		
		return dao.getAllByHql(hql, userId);
	}
	
	/**
	 * get goal by id
	 * 
	 * @param goalId
	 * @return
	 */
	public Goal getGoal(String goalId) {
		if(StringUtil.isNullOrEmpty(goalId)) {
			return new Goal();
		}
		
		return (Goal) dao.getObject(Goal.class, goalId);
	}
	
	/**
	 * save goal
	 * 
	 * @param goal
	 * @param userId
	 */
	public void saveGoal(Goal goal, String userId) {
		if(goal == null || StringUtil.isNullOrEmpty(userId)) {
			return;
		}
		
		if(StringUtil.isNullOrEmpty(goal.getId())) {
			goal.setId(Constants.getID());
			goal.setUid(userId);
			goal.setCreateTime(new Date());
		}
		
		goal.setModifyTime(new Date());
		
		dao.saveObject(goal);
	}
}
